<?php
/**
 * 注意：本内容仅限于博也公司内部传阅,禁止外泄以及用于其他的商业目的
 * @author    hebidu<346551990@qq.com>
 * @copyright 2018 www.itboye.com Boye Inc. All rights reserved.
 * @link      http://www.itboye.com/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 * Revision History Version
 ********1.0.0********************
 * file created @ 2018-03-12 17:26
 *********************************
 ********1.0.1********************
 *
 *********************************
 */

namespace by\component\tailong_bank\api;


use by\component\tailong_bank\context\BaseContext;
use by\component\tailong_bank\req\ApproveDevReq;
use by\component\tailong_bank\resp\ApproveDevResp;
use by\infrastructure\base\CallResult;
use by\infrastructure\helper\CallResultHelper;
use Psr\SimpleCache\CacheInterface;

class ApproveDevApi extends BaseApi
{

    public function __construct(CacheInterface $cache = null)
    {
        parent::__construct($cache);
        $this->setService("zjjr/approveDev");
    }

    /**
     * @param ApproveDevReq $req
     * @param BaseContext $context
     * @param int $cacheTime
     * @return CallResult
     * @throws \ErrorException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function call(ApproveDevReq $req, BaseContext $context)
    {
        $cacheTime = $context->getTokenCacheTime();
        $url = $context->getApiUrl().$this->getService();
        if ($cacheTime > 0) {
            // 取缓存
            $respJs = $this->getCache($context->getAppID());
            if ($respJs) {
                $respArr = json_decode($respJs, JSON_OBJECT_AS_ARRAY);
                if (is_array($respArr)) {
                    $resp = new ApproveDevResp($respArr);
                    return CallResultHelper::success($resp);
                }
            }
        }

        $sign = strtoupper(md5($req->getRandom().$req->getSeqNo().$context->getAppSecretKey()));
        $data = [
            'appID' => $context->getAppID(),
            'random' => $req->getRandom(),
            'seqNO' => $req->getSeqNo(),
            'sign' => $sign
        ];
        $result = $this->post($url, json_encode($data));
        if ($result->isSuccess()) {
            // 转化内容为 resp
            $resp = new ApproveDevResp($result->getData());
            if ($cacheTime > 0 && !empty($context->getAppID()) && !empty($resp->getAppAccessToken())) {
                $this->setCache($context->getAppID(), json_encode($resp->toArray()), $cacheTime);
            }

            return CallResultHelper::success($resp);
        }
        return $result;
    }
}